<template>
  <div>
    <div class="bbg1">
      <div class="title2">
        <div class="shuxian2"></div>
        <div class="wenzi2">日志列表</div>
      </div>
    </div>

    <el-row class="bbg1 pl45">
      <el-form :inline="true" :model="form">
        <el-form-item>
          <el-date-picker
            v-model="form.start_time"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="开始日期"
            style="width: 240px"
          >
          </el-date-picker>
          <span class="ml10 mr10" style="color: #fff">至</span>
          <el-date-picker
            v-model="form.end_time"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="结束日期"
            style="width: 240px"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-input
            v-model="form.id"
            placeholder="日志编号"
            style="width: 240px"
          ></el-input>
        </el-form-item>

        <!-- <el-form-item >
			<daterange v-bind:se.sync="s_e" type="daterange"></daterange>
	    </el-form-item> -->

        <el-form-item>
          <el-input
            v-model="form.release_name"
            placeholder="创建人"
            style="width: 240px"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-input
            v-model="form.log_title"
            placeholder="日志标题"
            style="width: 240px"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item >
		    <el-input v-model="form.status" placeholder="处理状态"></el-input>
		</el-form-item> -->
        <el-form-item>
          <el-select
            v-model="form.work_status"
            placeholder="工作类别"
            style="width: 240px"
          >
            <el-option
              v-for="(item,index) in status_select_label" :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-cascader
            style="width: 515px"
            filterable
            :options="treedata"
            :props="props1"
            filterable
            change-on-select
            v-model="selectedOptions"
          >
          </el-cascader>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="search"
            style="width: 140px; background: rgba(10, 137, 145, 1)"
            >查 询</el-button
          >
					<el-button
            type="primary"
            @click="report"
            style="width: 140px; background: rgba(10, 137, 145, 1)"
            >导 出 Excel</el-button
          >
        </el-form-item>
        <!-- <el-form-item>
		    <el-button type="success" @click="add">创建</el-button>
		</el-form-item> -->
      </el-form>
    </el-row>

    <el-row class="bbg2 pl45">
      <el-table
        :data="list.results"
        :header-cell-style="{
          'background-color': '#169098',
          color: '#fff',
        }"
        border
        height="680"
        style="background: #083749"
        :row-style="{
          height: '63px',
        }"
      >
        <el-table-column
          prop="id"
          label="日志编号"
          align="center"
          width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="work_status_name"
          label="工作类型"
          align="center"
          width="100"
        >
        </el-table-column>
        <el-table-column
          prop="log_title"
          label="日志标题"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column prop="grid_names" label="所属网格" align="center">
        </el-table-column>
        <el-table-column prop="release_name" label="创建人" align="center">
        </el-table-column>
        <el-table-column
          prop="responsibility_person"
          label="责任人"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="release_time"
          label="创建时间"
          align="center"
          show-overflow-tooltip
          width="170"
        >
        </el-table-column>

        <el-table-column align="center" width="70" label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.id"
              type="success"
              size="mini"
              icon="el-icon-view"
              circle
              @click="edit(scope.row)"
            >
            </el-button>
            <!-- <el-button type="danger" size="mini" 
	      		icon="el-icon-delete" circle
	      		@click="del(scope.row)">
	      		</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <el-row class="bbg1 text-center pt30 pb20">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next"
        :total="list.totalRecord"
      >
      </el-pagination>
    </el-row>

    <el-dialog
      :title="current.info.question_title"
      :visible.sync="dialogVisible"
      width="900px"
    >
      <eventinfo :obj="current"></eventinfo>
    </el-dialog>
  </div>
</template>

<script>
import daterange from "@/components/daterange";
import eventinfo from "./info_1";
import flowinfo from "./flow";

export default {
  name: "eventList",

  data() {
    return {
      list: {},

      form: {
        start_time: this.$util.date2str(new Date()),
        end_time: this.$util.date2str(new Date()),
      },

      pageNo: 1,
      pageSize: 10,

      current: {
        info: {},
        flow: {},
      },

      dialogVisible: false,

      task_type_label: ["", "紧急任务", "普通", "检查", "日常"],

      status_label: ["", "处理中", "已完成"],

      s_e: [this.$util.date2str(new Date()), this.$util.date2str(new Date())],

      props1: {
        value: "id",
        label: "name",
      },

			treedata: [],
			
			exportList: [],

      selectedOptions: ['88888'],

      activeName2: "first",

      status_select_label: [
        { label: "全部工作类型", value: undefined },
      ],
    };
  },

  props: {},

  components: {
    daterange,
    eventinfo,
    flowinfo,
  },

  computed: {},

  methods: {
    init() {
      const day = this.$util.dateDiff(this.form.start_time, this.form.end_time);
      if (day < 0) {
        this.$message.warning("开始时间不能在结束时间之后。");
        return;
      }

      this.$http({
        fun: "eventList",
        //requestType : 'get',
        ...this.form,
        start_time: this.form.start_time + " 00:00:00",
        end_time: this.form.end_time + " 23:59:59",
        grid_id: this.selectedOptions[this.selectedOptions.length - 1] + "",
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        cb: (res) => {
          console.log(res);
          this.list = this.$util.tableAdd(res);
        },
      });
		},
		
		initWorkList () {
			let data = {
				type: 'work_status'
			}
			this.$http({
        fun: "getDictItems",
        //requestType : 'get',
        ...data,
        cb: (res) => {
					// console.log('全部： ', this.$util.tableAdd(res))
					this.status_select_label = this.$util.tableAdd(res);
					this.status_select_label.unshift({ label: "全部工作类型", value: undefined })
        },
      });
		},

    add() {
      this.dialogVisible = true;
      this.current = {};
    },

    edit(item) {
      console.log(item);
      this.$http({
        fun: "eventInfo",
        id: item.id,
        cb: (res) => {
          this.$http({
            fun: "flowList",
            id: item.id,
            cb: (res1) => {
              console.log("ffffffff");
              console.log(res);
              console.log(res1);

              // res1.forEach(item => {
              // 	if(item.params == undefined || item.params == ''){
              // 		item['paramsobj'] = {
              // 			content : '',
              // 		};
              // 	}else{
              // 		//item['paramsobj'] = JSON.parse(item.params);
              // 		item['paramsobj'] = item.params;
              // 	}

              // 	// if(item.handle_time == undefined){
              // 	// 	item.handle_time = this.$util.date2str(new Date()) + ' 23:59:59';
              // 	// }
              // })

              //处理图片和视频
              // let imgs = [];
              // let videos = [];

              res1.forEach((item1) => {
                if (item1.params) {
                  item1["imgs"] = [];
                  item1["videos"] = [];
                  item1.params.forEach((item) => {
                    if (
                      item.type == "img" &&
                      item.value != null &&
                      item.value != ""
                    ) {
                      item1["imgs"] = item.value.split(",");
                    }
                    if (
                      item.type == "video" &&
                      item.value != null &&
                      item.value != ""
                    ) {
                      item1["videos"] = item.value.split(",");
                    }
                  });
                }
              });

              this.current = {
                info: {
                  ...res,
                  // imgs : res.question_img ? res.question_img.split(',') : [],
                  // videos : res.question_video ? res.question_video.split(',') : [],
                },
                flow: res1,
              };
              console.log(this.current);
              this.activeName2 = "first";
              this.dialogVisible = true;
            },
          });
        },
      });
    },

    del(item) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            fun: "createHelp",
            id: item.id,
            del_flag: 1,
            cb: (res) => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.init();
            },
            err: (res) => {
              this.$message({
                type: "error",
                message: "删除失败!",
              });
            },
          });
        })
        .catch(() => {});
    },

    save() {
      this.$http({
        fun: "createHelp",
        ...this.current,
        cb: (res) => {
          console.log(res);
          this.$message.success("操作成功");
          this.dialogVisible = false;
          this.init();
        },
      });
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.init();
    },

    handleCurrentChange(val) {
      this.pageNo = val;
      this.init();
    },

    search() {
      this.pageNo = 1;
      this.init();
		},

		report() {
			const day = this.$util.dateDiff(this.form.start_time, this.form.end_time);
      if (day < 0) {
        this.$message.warning("开始时间不能在结束时间之后。");
        return;
      }

      this.$http({
        fun: "eventList",
        ...this.form,
        start_time: this.form.start_time + " 00:00:00",
        end_time: this.form.end_time + " 23:59:59",
        grid_id: this.selectedOptions[this.selectedOptions.length - 1] + "",
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        cb: (res) => {
					this.exportList = this.$util.tableAdd(res).results;
					alert(JSON.stringify(this.exportList))
					if (this.exportList.length > 0) {
						this.export2Excel()
					}else{
						this.$message.warning('无导出数据');
					}
        },
      });
		},
		
		export2Excel() {
			require.ensure([], () => {
				const { export_json_to_excel } = require('@/views/vendor/Export2Excel');
				const tHeader =
					[
						'日志编号', '日志标题', '网格名称','内容',
						'工作类型','工作对象类型','日志类型', '责任人', '责任人电话', 
						'工作对象名称', '工作对象联系电话', '经度', '维度', '创建时间'
					];
				const filterVal =
					['id', 'log_title','grid_names','log_info',
						'work_status_name','work_obj_status_name', 'log_status_name', 'responsibility_person', 'responsibility_person_mobile',
						'work_obj_name', 'work_obj_tel', 'event_longitude', 'event_latitude', 'create_time'
					];
				const list = this.exportList;
				const data = this.formatJson(filterVal, list);
				export_json_to_excel(tHeader, data, '日志服务报表记录'+ this.$moment(new Date()).format('YYYYMMDDHHmmss'));

				this.$message.success('导出数据成功');
			})
		},
		formatJson(filterVal, jsonData) {
			return jsonData.map(v => filterVal.map(j => v[j]))
		},
		getGridList() {
			this.$http({
				fun: "grideList",
				cb: (res) => {
					const result = this.$util.transData(res, "id", "parent_id", "children");
					console.log(result);
					this.treedata = result;
					this.treedata.unshift({
						name: "全部网格",
						id: 88888,
					});
				},
			});
		}
  },

  watch: {},

  mounted() {
		this.init();
		this.initWorkList();
    this.getGridList();
  },
};
</script>

<style scoped>
</style>
